<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>素材库</title>
    <link rel="stylesheet" href="/static/admin/lib/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/admin/css/common.css" media="all">
    <link rel="stylesheet" href="/static/admin/css/material_library.css" media="all">
    <style>
        .layui-layer-setwin .layui-layer-close2 {
            padding: 0 !important;
            border: 0 !important;
            width: 20px !important;
            height: 20px !important;
        }

        .operation-btns {
            display: none;
            position: absolute;
            border-radius: 4px;
            width: 100%;
            line-height: 2;
            color: #fff;
            text-align: center;
            top: 0;
        }

        .img-title {
            overflow: hidden;
            width: 100%;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    </style>
</head>
<body>
<div class="admin-mdl">
    <div class="admin-mdl-content">
        <div class="left">
            <ul class="admin-mdl-file ">
                {foreach name="cate" item="vo" key='key'}
                <li class="{if $key == 0}active groupActive{/if} switchGroup contextmenu" data-id="{$vo.id}"
                    data-title="{$vo.title}">
                    <img src="/static/admin/images/material/icon35.png" alt="" class="folder">
                    <p>{$vo.title}</p>
                </li>
                {/foreach}
            </ul>
            <p class="btn flex-center">
                <button type="button" class="layui-btn layui-btn-primary addGroup">添加分组</button>
            </p>
        </div>
        <div class="center">
            <div>
                <div class="flex-layout admin-mdl-upd">
                    <button type="button" class="layui-btn uploadsBtn" style="height: 2.875rem;line-height: 2.875rem">
                        本地上传
                    </button>
                    <div>
                        <div class="admin-mdl-search">
                            <input type="text" placeholder="请输入名称" id="keyword">
                            <p class="flex-center search">
                                <img src="/static/admin/images/material/icon37.png" alt="">
                            </p>
                        </div>
                    </div>
                </div>
                <div class="admin-imgs-list type1">
                    <ul class="admin-imgs tpl_list" style="padding-top: 10px"></ul>
                </div>
            </div>
            <div class="page" id="page">
            </div>
        </div>
        <div class="rgt">
            <div class="flex-layout">已选择<span class="selectedCount">0</span>/<span>{$allowSelectedCount}</span>
                <p class="clearSelected"> 清空</p>
            </div>
            <p class="flex-center selected"
               style="display: flex;flex-direction: column;align-items: center;overflow: scroll; height: calc(100% - 7.25rem);justify-content: start">

            </p>
        </div>
    </div>

    <div class="admin-mdl-btm">
        <!--        <div class="layui-btn-container">-->
        <!--            <button type="button" class="layui-btn layui-btn-primary clearOpen">取消</button>-->
        <!--            <button type="button" class="layui-btn layui-btn-danger confirm">确认</button>-->
        <!--        </div>-->
    </div>
</div>
<input type="hidden" id="selectedUrl" value=''/>
</body>
<script id="template" type="text/html">
    {{# for(var i=0;i
    <d.data.length ;i++){ }}
    <li style="position: relative; cursor:pointer;"
        class="{{#  if(d.Ids.indexOf(d.data[i].url) >= 0){ }}active{{#  } }} parent parent-{{d.data[i].id}}">
        <div class="flex-center images-li" data-id="{{d.data[i].id}}" data-url="{{d.data[i].url}}">
            <img src="{{d.data[i].url}}" alt="">
            <div class="check-img flex-center">
                <img src="/static/admin/images/material/icon40.png" alt="">
            </div>
        </div>
        <div class="operation-btns text-xs text-center sub">
            <button data-id="{{d.data[i].id}}" class="clear layui-btn layui-btn-radius layui-btn-danger layui-btn-xs"
                    style="width: 43%">删除
            </button>
            <button data-url="{{d.data[i].url}}"
                    class="preview layui-btn layui-btn layui-btn-radius layui-btn-warm layui-btn-xs" style="width: 43%">
                查看
            </button>
        </div>
        <div class="img-title">{{d.data[i].title}}</div>
    </li>
    {{# } }}
</script>

<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/lib/layui/layui.js"></script>
<script>
    layui.use(['laypage', 'upload', 'laytpl', 'dropdown'], function () {
        var laypage = layui.laypage
            , upload = layui.upload
            , laytpl = layui.laytpl
            , selectedLength = 0
            , allowSelectedCount = parseInt('{$allowSelectedCount}')
            , selectedCount = $(".selectedCount")
            , selectedDiv = $(".selected")
            , selectedUrl = []
            , selectedIds = []
            , dropdown = layui.dropdown
            , count = "{$count}"
            , selectedUrlDom = $("#selectedUrl");


        //执行菜单
        dropdown.render({
            elem: '.contextmenu' //在 id="demo" 的元素中触发事件。也可以直接设置为 document，从而重置整个右键菜单
            , trigger: 'contextmenu' //右键事件
            , data: [{
                title: '命名分组'
                , type: 1
            }, {
                title: '删除分组'
                , type: 2
            }]
            , click: function (data, othis) {
                var id = this.elem.attr('data-id');
                if (data.type == 2) {
                    layer.confirm('删除分组后，分组内的文件也将同步删除<br/>如文件已被使用，请谨慎操作！', {title: "请确认"}, function (index) {
                        layer.close(index);
                        load();
                        $.ajax({
                            type: 'POST',
                            url: '{:url("materialLibrary/destroyGroup")}',
                            data: {id: id},
                            dataType: "json",
                            success: function (data) {
                                layer.msg(data.msg);
                                if (data.code == 1) {
                                    location.reload();
                                }
                            },
                            error(e) {
                                layer.msg('加载失败');
                                layer.closeAll();
                            }
                        });
                    });
                } else {
                    layer.prompt({title: '请填写要修改的分组名称', formType: 3}, function (pass, index) {
                        layer.close(index);
                        load();
                        var btn = $(this);
                        btn.attr('disabled', true);
                        $.ajax({
                            type: 'POST',
                            url: '{:url("materialLibrary/saveGroup")}',
                            data: {title: pass, id: id},
                            dataType: "json",
                            success: function (data) {
                                layer.closeAll();
                                if (data.code == 1) {
                                    window.location.reload();
                                } else {
                                    layer.msg(data.msg);
                                    btn.removeAttr('disabled');
                                }
                            },
                            error(e) {
                                layer.closeAll();
                                btn.removeAttr('disabled');
                            }
                        });
                        return false;
                    });
                }

            }
        });
        getData($('.groupActive').attr('data-id'), 1, 10, 'template', 'tpl_list')
        // //执行一个laypage实例
        // laypage.render({
        //     elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
        //     , count: count //数据总数，从服务端得到
        //     , jump: function (obj, first) {
        //
        //     }
        // });

        $(".search").click(function () {
            getData($('.groupActive').attr('data-id'), 1, 10, 'template', 'tpl_list', $("#keyword").val())
        });
        $('.tpl_list').on('mouseover', '.parent', function () {
            $(this).children('.sub').show()
        }).on('mouseout', '.parent', function () {
            $(this).children('.sub').hide()
        }).on('click', '.images-li', function () {
            var id = $(this).attr('data-id');
            var url = $(this).attr('data-url');
            if ($(this).parent().hasClass('active')) {
                $(this).parent().removeClass('active');
                $('.selected-img-' + id).remove();
                selectedLength -= selectedLength > 0 ? 1 : 0;
                selectedCount.text(selectedLength);
                selectedUrl.splice(selectedUrl.indexOf(url), 1);
                selectedIds.splice(selectedUrl.indexOf(id), 1);
            } else {
                if (allowSelectedCount === 1) {
                    $(this).parent().addClass('active').siblings().removeClass('active');
                    selectedCount.text(1);
                    selectedDiv.html('<div class="selected-img selected-img-' + id + '" style="text-align: center"><img src="' + url + '">' +
                        '<button data-url="' + url + '" data-id="' + id + '" type="button" class="layui-btn layui-btn-primary layui-btn-xs clearCheck" style="margin-top: 5px">取消选中</button>' +
                        '</div>');
                    selectedUrl = [];
                    selectedIds = [];
                    selectedUrl.push(url);
                    selectedIds.push(id.toString());
                    selectedUrlDom.val(selectedUrl.join(','));
                } else {
                    if (selectedLength >= allowSelectedCount) {
                        layer.msg('您最多只能选择' + allowSelectedCount + '张');
                        return false;
                    }
                    $(this).parent().addClass('active');
                    selectedCount.text(selectedLength + 1);
                    selectedLength += 1;
                    selectedDiv.append('<div class="selected-img selected-img-' + id + '" style="text-align: center"><img src="' + url + '">' +
                        '<button data-url="' + url + '" data-id="' + id + '" type="button" class="layui-btn layui-btn-primary layui-btn-xs clearCheck" style="margin-top: 5px">取消选中</button>' +
                        '</div>');
                    selectedUrl.push(url);
                    selectedIds.push(id.toString());
                    selectedUrlDom.val(selectedUrl.join(','));
                }
            }
        }).on('click', '.clear', function () {
            var id = $(this).attr('data-id');
            layer.confirm('确认删除后，本地或云存储文件也将同步删除<br/>如文件已被使用，请谨慎操作！', {title: "请确认"}, function (index) {
                layer.close(index);
                load();
                $.ajax({
                    type: 'POST',
                    url: '{:url("materialLibrary/destroy")}',
                    data: {id: id},
                    dataType: "json",
                    success: function (data) {
                        layer.msg(data.msg);
                        if (data.code == 1) {
                            getData($('.groupActive').attr('data-id'), 1, 10, 'template', 'tpl_list', $("#keyword").val())
                        }
                    },
                    error(e) {
                        layer.msg('加载失败');
                        layer.closeAll();
                    }
                });
            });
        }).on('click', '.preview', function () {

            var value = $(this).attr("data-url").split(',');
            var data = [];
            for (i in value) {
                data.push({src: value[i]});
            }
            layer.photos({
                photos: {"data": data, "start": 0}
                , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机
                , closeBtn: 1,
            });
        });

        selectedDiv.on('click', '.clearCheck', function () {
            var id = $(this).attr("data-id");
            var url = $(this).attr('data-url');
            $('.parent-' + id).removeClass('active');
            $('.selected-img-' + id).remove();
            selectedLength -= selectedLength > 0 ? 1 : 0;
            selectedCount.text(selectedLength);
            selectedUrl.splice(selectedUrl.indexOf(url), 1);
            selectedIds.splice(selectedUrl.indexOf(id), 1);
        })

        $(".clearSelected").click(function () {
            $(".selected").html('')
            $(".selectedCount").text(0);
            $(".parent").removeClass('active');
            selectedLength = 0;
            selectedUrl = [];
            selectedIds = [];
        });
        $(".switchGroup").click(function () {
            $(this).addClass('active groupActive').siblings().removeClass('active groupActive');
            getData($(this).attr('data-id'), 1, 10, 'template', 'tpl_list', $("#keyword").val())
        });

        // $(".clearOpen").click(function (){
        //     var index = parent.layer.getFrameIndex(window.name);
        //     parent.layer.close(index);
        // });
        //
        // $(".confirm").click(function (){
        //     parent.getOpenImageValue(selectedUrl,'{$id}','{$name}');
        //     var index = parent.layer.getFrameIndex(window.name);
        //     parent.layer.close(index);
        // });

        function getData(cate, page, limit, now_tpl, par, keyword) {
            $("." + par).empty();
            load()
            $.ajax({
                type: 'GET',
                url: '{:url("materialLibrary/index")}',
                data: {cate: cate, page: page, limit: limit, keyword: keyword},
                dataType: "json",
                success: function (data) {
                    if (data.code == 0) {
                        if (data.data.length <= 0) {
                            $("." + par).html('<li style="width: 100%">暂无更多</li>');
                        } else {
                            var tpl = document.getElementById(now_tpl).innerHTML;
                            laytpl(tpl).render({data: data.data, Ids: selectedUrl}, function (html) {
                                $("." + par).html(html);
                            });
                        }
                        count = data.count
                        //执行一个laypage实例
                        if (page == 1) {
                            laypage.render({
                                elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
                                , count: count //数据总数，从服务端得到
                                , jump: function (obj, first) {
                                    if (!first) {
                                        getData($('.groupActive').attr('data-id'), obj.curr, obj.limit, 'template', 'tpl_list')
                                    }
                                }
                            });
                        }

                        layer.closeAll();
                    } else {
                        layer.msg(data.msg);
                    }
                },
                error(e) {
                    layer.closeAll();
                }
            });
        }


        $(".addGroup").click(function () {
            layer.prompt({title: '请填写分组名称', formType: 3}, function (pass, index) {
                layer.close(index);
                load();
                var btn = $(this);
                btn.attr('disabled', true);
                $.ajax({
                    type: 'POST',
                    url: '{:url("materialLibrary/addGroup")}',
                    data: {title: pass},
                    dataType: "json",
                    success: function (data) {
                        layer.closeAll();
                        if (data.code == 1) {
                            window.location.reload();
                        } else {
                            layer.msg(data.msg);
                            btn.removeAttr('disabled');
                        }
                    },
                    error(e) {
                        layer.closeAll();
                        btn.removeAttr('disabled');
                    }
                });
                return false;
            });
        });

        function load() {
            layer.msg('<div><i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中....', {
                shade: 0.4,
                time: 99999
            });
        }

        upload.render({
            elem: '.uploadsBtn',
            url: '{:url("uploads/uploadImageMaterial")}',
            multiple: true,
            data: {
                cate: function () {
                    return $('.groupActive').attr('data-id');
                }
            },
            before: function (obj) {
                var i = this.elem.index('.uploadsBtn');
                load();
            },
            done: function (data) {
                layer.closeAll();
                if (data.code == 200) {
                    getData($('.groupActive').attr('data-id'), 1, 10, 'template', 'tpl_list')
                } else {
                    layer.msg(data.msg);
                }
            },
            error: function () {
                layer.closeAll();
                layer.msg('上传失败');
            }
        });
    })


</script>
</html>